<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use think\facade\Config;
use Xin\Thinkphp5\Support\OS;

class ResourceManager{

	/**
	 * @var array
	 */
	private static $data = [];

	/**
	 * 初始化数据
	 *
	 * @param string $key
	 */
	private static function initData($key){
		if(isset(self::$data[$key])){
			return;
		}

		self::$data[$key] = [];
	}

	/**
	 * 压入一个资源
	 *
	 * @param string $name
	 * @param string $path
	 */
	public static function push($name, $path){
		self::initData($name);

		$list = &self::$data[$name];

		if(!array_search($path, $list)){
			$list[] = $path;
		}

		unset($list);
	}

	/**
	 * 压入一个js文件路径
	 *
	 * @param string $path
	 */
	public static function js($path){
		self::push('js', $path);
	}

	/**
	 * 使用模块相对路径压入一个js文件路径
	 *
	 * @param string $path
	 */
	public static function jsWithModulePath($path){
		$path = OS::getWebJsPath().'/'.$path;
		self::js($path);
	}

	/**
	 * 生成 script js标签
	 *
	 * @return string
	 */
	public static function buildJsToString(){
		self::initData('js');
		$list = &self::$data['js'];

		$result = '';
		$resVersion = self::getVersion();
		foreach($list as $path){
			$result .= "<script src=\"{$path}?r={$resVersion}\"></script>\n";
		}

		return $result;
	}

	/**
	 * 获取版本号
	 *
	 * @return string
	 */
	private static function getVersion(){
		$resVersion = Config::get('web.res_version');
		if(empty($resVersion)){
			$resVersion = 'v1.0.0';
		}
		return OS::isLocal() ? time() : $resVersion;
	}
}
